/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.contentField;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.model.core.ActionPage;
import com.blandware.atleap.model.core.ContentField;
import com.blandware.atleap.model.core.ContentPage;
import com.blandware.atleap.model.core.Layout;
import com.blandware.atleap.model.core.Localizable;
import com.blandware.atleap.service.core.ContentFieldManager;
import com.blandware.atleap.service.core.LookupManager;
import com.blandware.atleap.service.exception.BeanAlreadyExistsException;
import com.blandware.atleap.service.exception.OwnerNotFoundException;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.ContentFieldForm;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

/**
 * <p>Creates new content field
 * </p>
 * <p><a href="CreateContentFieldAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @author Andrey Grebnev <a href="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
 * @version $Revision: 1.34 $ $Date: 2008/04/29 17:48:05 $
 * @struts.action path="/core/contentField/create"
 * name="contentFieldForm"
 * scope="request"
 * input="inputForward"
 * validate="true"
 * roles="core-contentField-create, core-contentField-override, core-contentField-createIndexed"
 * @struts.action-forward name="inputForward"
 * path=".core.contentField.create"
 * @struts.action-forward name="viewContentField"
 * path="/core/contentField/view.do"
 * redirect="true"
 * @struts.action-forward name="listContentFields"
 * path="/core/contentField/list.do"
 * redirect="false"
 * @struts.action-forward name="unsatisfiable"
 * path="/core/contentField/list.do"
 */
public final class CreateContentFieldAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

		ContentFieldForm contentFieldForm = (ContentFieldForm) form;
		Long ownerId;
		if ( !GenericValidator.isBlankOrNull(contentFieldForm.getOwnerId()) ) {
			ownerId = Long.valueOf(contentFieldForm.getOwnerId());
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing owner ID. Returning to index...");
			}
			return mapping.findForward("admin");
		}

		request.getSession().setAttribute(WebappConstants.OWNER_ID_KEY, ownerId);

		if ( !isCancelled(request) ) {
			LookupManager lookupManager = (LookupManager) getBean(Constants.LOOKUP_MANAGER_BEAN);
			Localizable owner = lookupManager.retrieveLocalizable(ownerId);

			if ( owner == null ) {
				ActionMessages errors = new ActionMessages();
				errors.add("ownerNotFound", new ActionMessage("core.contentField.errors.ownerNotFound"));
				saveErrors(request, errors);
				return mapping.findForward("admin");
			}

			String fieldIdentifier = contentFieldForm.getIdentifier();

            // check whether trying to change indexability
            if (owner instanceof ContentPage || owner instanceof ActionPage) {
                Set indexedFieldIdentifiers = WebappUtil.getIndexedOverridableFieldIdentifiers(owner, request);
                Set unIndexedFieldIdentifiers = WebappUtil.getUnIndexedOverridableFieldIdentifiers(owner, request);
                Set intersection = new HashSet(indexedFieldIdentifiers);
                intersection.retainAll(unIndexedFieldIdentifiers);
                if ( !intersection.contains(fieldIdentifier) ) {
                    if ( !GenericValidator.isBlankOrNull(contentFieldForm.getIndex()) ) {
                        if ( unIndexedFieldIdentifiers.contains(fieldIdentifier) ) {
                            ActionMessages errors = new ActionMessages();
                            errors.add("contentFieldUnexpectedIndex", new ActionMessage("core.contentField.errors.unexpectedIndex"));
                            saveErrors(request, errors);
                            saveToken(request);
                            return mapping.getInputForward();
                        }
                    } else {
                        if ( indexedFieldIdentifiers.contains(fieldIdentifier) ) {
                            ActionMessages errors = new ActionMessages();
                            errors.add("contentFieldIndexExpected", new ActionMessage("core.contentField.errors.indexExpected"));
                            saveErrors(request, errors);
                            saveToken(request);
                            return mapping.getInputForward();
                        }
                    }
                }
            } else if (owner instanceof Layout) {
                Layout ownerLayout = (Layout) owner;
                Set indexedFieldIdentifiers = WebappUtil.getIndexedFieldIdentifiers(ownerLayout.getDefinition(), request);
                Set unIndexedFieldIdentifiers = WebappUtil.getUnIndexedFieldIdentifiers(ownerLayout.getDefinition(), request);
                Set intersection = new HashSet(indexedFieldIdentifiers);
                intersection.retainAll(unIndexedFieldIdentifiers);
                if ( !intersection.contains(fieldIdentifier) ) {
                    if ( !GenericValidator.isBlankOrNull(contentFieldForm.getIndex()) ) {
                        if ( unIndexedFieldIdentifiers.contains(fieldIdentifier) ) {
                            ActionMessages errors = new ActionMessages();
                            errors.add("contentFieldUnexpectedIndex", new ActionMessage("core.contentField.errors.unexpectedIndex"));
                            saveErrors(request, errors);
                            saveToken(request);
                            return mapping.getInputForward();
                        }
                    } else {
                        if ( indexedFieldIdentifiers.contains(fieldIdentifier) ) {
                            ActionMessages errors = new ActionMessages();
                            errors.add("contentFieldIndexExpected", new ActionMessage("core.contentField.errors.indexExpected"));
                            saveErrors(request, errors);
                            saveToken(request);
                            return mapping.getInputForward();
                        }
                    }
                }
            }

			if ( owner instanceof ContentPage || (owner instanceof Layout && !request.isUserInRole("core-contentField-create") || (owner instanceof ActionPage && !request.isUserInRole("core-contentField-create"))) ) {
				Set identifiers = null;
				if ( owner instanceof ContentPage || owner instanceof ActionPage ) {
                    // Overriding field
                    if ( !request.isUserInRole("core-contentField-override") ) {
                        response.sendError(HttpServletResponse.SC_FORBIDDEN);
                        return null;
                    }
					identifiers = WebappUtil.getOverridableFieldIdentifiers(owner, request);

					if ( !identifiers.contains(fieldIdentifier) ) {
						ActionMessages errors = new ActionMessages();
						errors.add("contentFieldIncorrectIdentifier", new ActionMessage("core.contentField.errors.incorrectIdentifier"));
						saveErrors(request, errors);
						saveToken(request);
						return mapping.getInputForward();
					}
				} else {
                    // Creating new index or overriding field
                    boolean canCreateIndexed = request.isUserInRole("core-contentField-createIndexed");
                    boolean canOverride = request.isUserInRole("core-contentField-override");
                    if ( !canCreateIndexed && !canOverride ) {
                        response.sendError(HttpServletResponse.SC_FORBIDDEN);
                        return null;
                    }
					Layout ownerLayout = (Layout) owner;
                    if (canCreateIndexed) {
                        identifiers = WebappUtil.getIndexedFieldIdentifiers(ownerLayout.getDefinition(), request);
                        if (identifiers == null) {
                            identifiers = new TreeSet();
                        }
                    }
                    if (canOverride) {
                        identifiers.addAll(WebappUtil.getOverridableFieldIdentifiers(ownerLayout, request));
                    }
                    if ( !identifiers.contains(fieldIdentifier) ) {
						ActionMessages errors = new ActionMessages();
						errors.add("contentFieldIncorrectIdentifier", new ActionMessage("core.contentField.errors.incorrectIdentifier"));
						saveErrors(request, errors);
						saveToken(request);
						return mapping.getInputForward();
					}
				}
			} else {
                // (it's AP or Layout and user can create fields) OR (its not CP,
                // AP or Layout)
                if ( !request.isUserInRole("core-contentField-create") ) {
				    response.sendError(HttpServletResponse.SC_FORBIDDEN);
				    return null;
			    }
            }

			ContentField contentField = new ContentField();
			WebappUtil.copyProperties(contentField, contentFieldForm, request);
			if ( !GenericValidator.isBlankOrNull(contentFieldForm.getIndex()) ) {
				fieldIdentifier += "[" + contentFieldForm.getIndex() + "]";
				contentField.setIdentifier(fieldIdentifier);
			}
			contentField.setInternal(Boolean.FALSE);

			ContentFieldManager contentFieldManager = (ContentFieldManager) getBean(Constants.CONTENT_FIELD_MANAGER_BEAN);

			Long contentFieldId;
			try {
				contentFieldId = contentFieldManager.createContentField(contentField, ownerId);
			} catch ( OwnerNotFoundException e ) {
				ActionMessages errors = new ActionMessages();
				errors.add("ownerNotFound", new ActionMessage("core.contentField.errors.ownerNotFound"));
				saveErrors(request, errors);
				return mapping.findForward("admin");
			} catch ( BeanAlreadyExistsException e ) {
				// contentField already exists
				ActionMessages errors = new ActionMessages();
				errors.add("contentFieldAlreadyExists", new ActionMessage("core.contentField.errors.alreadyExists"));
				saveErrors(request, errors);
				saveToken(request);
				return mapping.getInputForward();
			}
			request.getSession().setAttribute(WebappConstants.CONTENT_FIELD_ID_KEY, contentFieldId);
			return mapping.findForward("viewContentField");
		} else {
			// action was cancelled - return to page with list of content fields
			return mapping.findForward("listContentFields");
		}
	}
}